/*
 * @Author: your name
 * @Date: 2021-06-02 11:23:26
 * @LastEditTime: 2021-06-02 16:37:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_island_api\app\services\wx.js
 */
const util = require('util')
const axios = require('axios')
const { User } = require('../models/user')
const { generateToken } = require('../../core/utils')
const { Auth } = require('../../middlewares/auth')

class WXManager {
    // 获取code
    static async codeToToken(code) {
        const url = util.format(global.config.wx.loginUrl,
            global.config.wx.appId,
            global.config.wx.appSecret,
            code)
        
        const result = await axios.get(url)
        if (result.status !== 200) {
            throw new global.errs.AuthFailed('openid获取失败')
        }
        const errmsg = result.data.errmsg
        const errCode = result.data.errCode
        if (errCode) {
            throw new global.errs.AuthFailed('openid获取失败:' + errmsg)
        }
        // 查询openid
        let user = await User.getUserByOpenid(result.data.openid)
        // 不存在则注册
        if (!user) {
            user = await User.registerByOpenid(result.data.openid)
        }
        // 生成并返回token
        return generateToken(user.id, Auth.USER)
    }
}

module.exports = {
    WXManager
}
